package team.bluepen.supermarket.web.filter;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.constant.Role;
import team.bluepen.supermarket.data.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Kai
 */
@WebFilter(filterName = "UserRoleFilter", urlPatterns = "/account.jsp")
public class UserRoleFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute(Constant.SESSION_USER);

        if (user == null || user.getRole() == null) {
            resp.sendRedirect("/");
            return;
        }
        if (user.getRole() == Role.USER || user.getRole() == Role.GUEST) {
            resp.sendRedirect("overview.jsp");
            return;
        }
        if (user.getRole() == Role.ADMIN) {
            chain.doFilter(request, response);
        }
    }
}
